#include <iostream>
#include <algorithm>
#include <string>
#include <cstdio>
#include <vector>
#include <stack>
#include <queue>
#include <set>
using namespace std;
class Solution
{
public:
    int minKBitFlips(vector<int> &A, int K)
    {
        queue<int> que;
        int index = 0, i = 0, cnt = 0;
        while (index < A.size() && A[index] == 1)
            index++;
        if (index >= A.size())
            return cnt;
        que.push(index), cnt++;
        for (i = index + 1; i < A.size(); ++i)
        {
            if (que.empty() == false && que.front() + K <= i)
                que.pop();
            if (que.size() % 2 == A[i])
                que.push(i), cnt++;
        }
        if (que.empty() == false && que.front() + K <= i)
            que.pop();
        if (que.empty() == false && que.front() + K > A.size())
            cnt = -1;
        return cnt;
    }
};